package com.system.connect.springboot_flowers.controller;

import com.system.connect.springboot_flowers.dto.OrderCreateDTO;
import com.system.connect.springboot_flowers.entity.Order;
import com.system.connect.springboot_flowers.entity.OrderItem;
import com.system.connect.springboot_flowers.service.OrderService;
import com.system.connect.springboot_flowers.utils.R;
import com.system.connect.springboot_flowers.utils.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/orders")
@Validated
public class OrderController {

    @Autowired
    private OrderService orderService;

    @PostMapping("/create")
    public R<Order> createOrder(@Valid @RequestBody OrderCreateDTO orderCreateDTO) {
        try {
            Integer userid = Integer.valueOf(TokenUtils.getUser());
            Order order = orderService.createOrder(orderCreateDTO, Long.valueOf(userid));
            return R.success(order);
        } catch (NumberFormatException e) {
            return R.error("用户ID格式错误");
        } catch (Exception e) {
            return R.error("创建订单失败：" + e.getMessage());
        }
    }

    @GetMapping("/{id}")
    public R<Order> getOrder(@PathVariable Long id) {
        try {
            Order order = orderService.getOrderById(id);
            return R.success(order);
        } catch (Exception e) {
            return R.error("获取订单失败：" + e.getMessage());
        }
    }

    @PutMapping("/{id}/status")
    public R<Order> updateOrderStatus(@PathVariable Long id, @RequestParam Integer status) {
        try {
            Order updatedOrder = orderService.updateOrderStatus(id, status);
            return R.success(updatedOrder);
        } catch (Exception e) {
            return R.error("更新订单状态失败：" + e.getMessage());
        }
    }

    @GetMapping("/list")
    public R<List<Order>> getOrderList(
            @RequestParam(required = false) Integer status,
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size) {
        try {
            Integer userId = Integer.valueOf(TokenUtils.getUser());
            List<Order> orders = orderService.getOrderList(Long.valueOf(userId), status, page, size);
            return R.success(orders);
        } catch (NumberFormatException e) {
            return R.error("用户ID格式错误");
        } catch (Exception e) {
            return R.error("获取订单列表失败：" + e.getMessage());
        }
    }

    /**
     * 管理员获取全部账单
     * @param status 订单状态筛选(可选)
     * @param page 页码(默认1)
     * @param size 每页数量(默认10)
     * @return 订单列表
     */
    @GetMapping("/admin/list")
    public R<List<Order>> getAllOrders(
            @RequestParam(required = false) Integer status,
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size) {
        try {
            // 管理员获取所有账单，不需要传入用户ID
            List<Order> orders = orderService.getOrderList(null, status, page, size);
            return R.success(orders);
        } catch (Exception e) {
            return R.error("获取订单列表失败：" + e.getMessage());
        }
    }
    
    /**
     * 管理员查看订单详情
     * @param id 订单ID
     * @return 订单详情
     */
    @GetMapping("/admin/detail/{id}")
    public R<Map<String, Object>> getOrderDetail(@PathVariable Long id) {
        try {
            Map<String, Object> orderDetail = orderService.getOrderDetail(id);
            return R.success(orderDetail);
        } catch (Exception e) {
            return R.error("获取订单详情失败：" + e.getMessage());
        }
    }
    
    /**
     * 管理员删除订单
     * @param id 订单ID
     * @return 删除结果
     */
    @DeleteMapping("/admin/delete/{id}")
    public R<String> deleteOrder(@PathVariable Long id) {
        try {
            boolean result = orderService.removeById(id);
            return result ? R.success("删除订单成功") : R.error("删除订单失败");
        } catch (Exception e) {
            return R.error("删除订单失败：" + e.getMessage());
        }
    }

    /**
     * 获取订单统计信息（管理员接口）
     * @param startDate 开始日期 (可选，格式：yyyy-MM-dd)
     * @param endDate 结束日期 (可选，格式：yyyy-MM-dd)
     * @return 订单统计信息
     */
    @GetMapping("/admin/statistics")
    public R<Map<String, Object>> getOrderStatistics(
            @RequestParam(required = false) String startDate,
            @RequestParam(required = false) String endDate) {
        try {
            Map<String, Object> statistics = new HashMap<>();
            
            // 处理日期参数
            LocalDateTime startDateTime = null;
            LocalDateTime endDateTime = null;
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            
            if (startDate != null && !startDate.isEmpty()) {
                LocalDate date = LocalDate.parse(startDate, formatter);
                startDateTime = date.atStartOfDay();
            }
            
            if (endDate != null && !endDate.isEmpty()) {
                LocalDate date = LocalDate.parse(endDate, formatter);
                endDateTime = date.plusDays(1).atStartOfDay(); // 包含结束日期的全天
            }
            
            // 获取订单总数
            int totalOrders = orderService.countOrders(startDateTime, endDateTime);
            statistics.put("totalOrders", totalOrders);
            
            // 获取已支付订单数量
            int paidOrders = orderService.countOrdersByStatus(1, startDateTime, endDateTime); // 假设1表示已支付状态
            statistics.put("paidOrders", paidOrders);
            
            // 获取未支付订单数量
            int unpaidOrders = orderService.countOrdersByStatus(0, startDateTime, endDateTime); // 假设0表示未支付状态
            statistics.put("unpaidOrders", unpaidOrders);
            
            // 获取总销售额
            double totalAmount = orderService.sumOrderAmount(startDateTime, endDateTime);
            statistics.put("totalAmount", totalAmount);
            
            // 获取各花种销售数量（Top 5）
            List<Map<String, Object>> topFlowers = orderService.getTopSellingFlowers(5, startDateTime, endDateTime);
            statistics.put("topSellingFlowers", topFlowers);
            
            // 获取销售趋势（最近7天）
            List<Map<String, Object>> salesTrend = orderService.getSalesTrend(7);
            statistics.put("salesTrend", salesTrend);
            
            return R.success(statistics);
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("获取订单统计信息失败：" + e.getMessage());
        }
    }

    /**
     * 取消订单（管理员接口）
     * @param id 订单ID
     * @param reason 取消原因
     * @return 取消结果
     */
    @PutMapping("/admin/cancel/{id}")
    public R<Order> cancelOrder(@PathVariable Long id, @RequestParam String reason) {
        try {
            Order order = orderService.cancelOrder(id, reason);
            return R.success(order);
        } catch (Exception e) {
            return R.error("取消订单失败：" + e.getMessage());
        }
    }

    /**
     * 批量更新订单状态（管理员接口）
     * @param orderIds 订单ID列表
     * @param status 目标状态
     * @return 更新结果
     */
    @PutMapping("/admin/batchUpdate")
    public R<String> batchUpdateOrderStatus(@RequestBody List<Long> orderIds, @RequestParam Integer status) {
        try {
            boolean result = orderService.batchUpdateOrderStatus(orderIds, status);
            return result ? R.success("批量更新订单状态成功") : R.error("批量更新订单状态失败");
        } catch (Exception e) {
            return R.error("批量更新订单状态失败：" + e.getMessage());
        }
    }

    /**
     * 获取订单项（管理员接口）
     * @param orderId 订单ID
     * @return 订单项列表
     */
    @GetMapping("/admin/items/{orderId}")
    public R<List<OrderItem>> getOrderItems(@PathVariable Long orderId) {
        try {
            List<OrderItem> orderItems = orderService.getOrderItems(orderId);
            return R.success(orderItems);
        } catch (Exception e) {
            return R.error("获取订单项失败：" + e.getMessage());
        }
    }

    /**
     * 获取用户消费排行（管理员接口）
     * @param limit 返回数量
     * @param startDate 开始日期
     * @param endDate 结束日期
     * @return 用户消费排行
     */
    @GetMapping("/admin/userRank")
    public R<List<Map<String, Object>>> getUserRankByAmount(
            @RequestParam(defaultValue = "10") Integer limit,
            @RequestParam(required = false) String startDate,
            @RequestParam(required = false) String endDate) {
        try {
            LocalDateTime startDateTime = null;
            LocalDateTime endDateTime = null;
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            
            if (startDate != null && !startDate.isEmpty()) {
                LocalDate date = LocalDate.parse(startDate, formatter);
                startDateTime = date.atStartOfDay();
            }
            
            if (endDate != null && !endDate.isEmpty()) {
                LocalDate date = LocalDate.parse(endDate, formatter);
                endDateTime = date.plusDays(1).atStartOfDay(); // 包含结束日期
            }
            
            List<Map<String, Object>> userRank = orderService.getUserRankByAmount(limit, startDateTime, endDateTime);
            return R.success(userRank);
        } catch (Exception e) {
            return R.error("获取用户消费排行失败：" + e.getMessage());
        }
    }

    /**
     * 导出订单数据（管理员接口）
     * @param startDate 开始日期
     * @param endDate 结束日期
     * @param status 订单状态
     * @return 导出文件路径
     */
    @GetMapping("/admin/export")
    public R<String> exportOrders(
            @RequestParam(required = false) String startDate,
            @RequestParam(required = false) String endDate,
            @RequestParam(required = false) Integer status) {
        try {
            LocalDateTime startDateTime = null;
            LocalDateTime endDateTime = null;
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            
            if (startDate != null && !startDate.isEmpty()) {
                LocalDate date = LocalDate.parse(startDate, formatter);
                startDateTime = date.atStartOfDay();
            }
            
            if (endDate != null && !endDate.isEmpty()) {
                LocalDate date = LocalDate.parse(endDate, formatter);
                endDateTime = date.plusDays(1).atStartOfDay(); // 包含结束日期
            }
            
            String filePath = orderService.exportOrders(startDateTime, endDateTime, status);
            return R.success(filePath);
        } catch (Exception e) {
            return R.error("导出订单数据失败：" + e.getMessage());
        }
    }
}
